import Fetch, { Cookie } from '@wattjs/network'
import { message as messageModel } from 'ant-design-vue'

const http = new Fetch({
  config: {
    APP_ID: process.env.VUE_APP_APP_ID || '',
    BASE_URL: process.env.VUE_APP_BASE_URL || '',
    XSRF_HEADER: process.env.VUE_APP_XSRF_HEADER || 'x-basement-token', // withCredentials true时，需要设置此header
    REQUEST_TIMEOUT: process.env.VUE_APP_REQUEST_TIMEOUT || 5000
  },
  transformRequest: [(data, headers) => {
    const token = Cookie.get(process.env.VUE_APP_XSRF_HEADER)
    if (token) Object.assign(headers, { Authorization: `Bearer ${token}` })
    return data
  }],
  showToast: (content) => {
    // 错误提示
    messageModel.error(content, 2.5)
  },
  // 格式不验证，再进行错误提示
  transformResponse: [
    (data) => {
      if (typeof data === 'string') {
        const res = JSON.parse(data)
        const msg = res.msg || res.message
        if (res.code === 111) window.location.replace(`${process.env.VUE_APP_LOGIN_URL}?fromUrl=${encodeURIComponent(window.location.href)}`)
        else if (process.env.VUE_APP_SUCCESS_CODE !== res.code && msg) messageModel.error(msg, 2.5)
      }
      return data
    }
  ]
})

export default http
